//
//  HORecordView.m
//  微度报修
//
//  Created by foguo-mac-1 on 6/6/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HORecordView.h"
#import "HOUtils.h"
#import "HODefine.h"
#import "HOAudioPlayer.h"
#import "AudioRecorder.h"
#import "HODefaultImage.h"
#import "HOUIMgr.h"
#import "HOConstants.h"

//static CGFloat MAX_AUDIO_TOTAL_TIME = 60.0f; //Seconds 
static CGFloat MIN_AUIDO_BUBBLE_WIDTH = 35.0;
@interface HOVoiceView : HOBaseView
@property(nonatomic, retain)UIButton 				*voiceBtn;
@property(nonatomic, retain)UIImageView 			*volumnImageView;
@property(nonatomic, retain)UILabel 				*durationLbl;
@property(nonatomic, retain)HORecordView 			*recordView;
@property(nonatomic, retain)UIActivityIndicatorView *loadingView;
@property(nonatomic, retain)NSTimer *timer;
@property(nonatomic, assign)int indicationIndex;
- (void)cleanup;
- (void)updateVolumnImg:(int)index;
- (void)showLoading:(BOOL)show;
- (void)stopAudioIndication;
- (void)startAudioIndication;
@end

@implementation HOVoiceView

- (instancetype)initWithFrame:(CGRect)frame
{
	self = [super initWithFrame:frame];
	if(self)
	{
		[self initSubviews];
		[self updateUI];
	}
	return self;
}

- (void)initSubviews
{
	[self initVoiceBtn];
	[self initVolumnImageView];
	[self initDurationView];
//	[self initLoadingView];
}

- (void)startAudioIndication
{
	[self invalidateTimer];
	self.timer = [NSTimer scheduledTimerWithTimeInterval: 0.3
												  target: self
												selector: @selector(handleTimer:)
												userInfo: nil
												 repeats: YES];
	[self.timer fire];
}

- (void)invalidateTimer
{
	[self.timer invalidate];
	self.timer = nil;
}

- (void)stopAudioIndication
{
	[self invalidateTimer];
	[self updateVolumnImg:2];
}

- (void)handleTimer:(NSTimer *)timer
{
	self.indicationIndex ++;
	NSInteger count = [[[HODefaultImage getInstance] getAudioIndicateImgArray] count] ;
	if(self.indicationIndex == count)
		self.indicationIndex = 0;
	[self updateVolumnImg:self.indicationIndex];
}

- (void)initLoadingView
{
	self.loadingView = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
	self.loadingView.frame = CGRectMake(110,
									0,
									20,
									20);
	[self addSubview:self.loadingView];
	[self.loadingView startAnimating];
	self.loadingView.hidden = YES;
}

- (void)initVoiceBtn
{
	UIImage *voiceImg = [UIImage imageNamed:@"baoxiuxiangqing_fangkuai"];
	self.voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	self.voiceBtn.frame = CGRectMake(0,
									  (self.frame.size.height - voiceImg.size.height) / 2,
									  0,
									  voiceImg.size.height);
	
	UIEdgeInsets insets = UIEdgeInsetsMake(0, 20, 0, 10);
	voiceImg = [voiceImg resizableImageWithCapInsets:insets];
	[self.voiceBtn setBackgroundImage:voiceImg forState:UIControlStateNormal];
	[self.voiceBtn addTarget:self action:@selector(didClickVoice) forControlEvents:UIControlEventTouchUpInside];
	[self addSubview:self.voiceBtn];
}

- (void)didClickVoice
{
	[self.recordView playAudio];
}

- (void)initVolumnImageView
{
//	UIView *volumnView = [[UIView alloc]initWithFrame:CGRectMake(98, 45, 9, 11)];
//	[self addSubview:volumnView];
	self.volumnImageView = [[[UIImageView alloc]initWithFrame:CGRectMake(HO_HORIZONAL_PADDING, (50 - 11) / 2, 8, 11)] autorelease];
	[self addSubview:self.volumnImageView];
//	[self addSubview:volumnView];
//	self.volumnImageView.layer.borderWidth = 1;
	[self updateVolumnImg:2];
}

- (void)initDurationView
{
	self.durationLbl = [[[UILabel alloc] initWithFrame:CGRectMake(0, (self.frame.size.height - 22) / 2, 22, 22)] autorelease];
	self.durationLbl.font = [UIFont systemFontOfSize:13];
	self.durationLbl.textColor = TEXT_COLOR_666666;
	self.durationLbl.text = @"";
	[self addSubview:self.durationLbl];
}

- (void)updateUI
{
	self.durationLbl.frame = CGRectMake(self.voiceBtn.frame.size.width + 1 * HO_HORIZONAL_PADDING,
										self.durationLbl.frame.origin.y,
										40,
										self.durationLbl.frame.size.height);
	self.loadingView.frame = CGRectMake(self.durationLbl.frame.origin.x + self.durationLbl.frame.size.width,
										self.durationLbl.frame.origin.y + (self.durationLbl.frame.size.height - self.loadingView.frame.size.height) / 2,
										self.loadingView.frame.size.width,
										self.loadingView.frame.size.height);
}

- (void)cleanup
{
	self.voiceBtn.frame = CGRectMake(self.voiceBtn.frame.origin.x, self.voiceBtn.frame.origin.y, 0, self.voiceBtn.frame.size.height);
	self.durationLbl.text = @"";
	[self updateUI];
}

- (void)showLoading:(BOOL)show
{
	if(show)
	{
		self.loadingView.hidden = NO;
		if(!self.loadingView.isAnimating)
			[self.loadingView startAnimating];
	}
	else
	{
		self.loadingView.hidden = YES;
		[self.loadingView stopAnimating];
	}
	
}

- (void)setTotalTime:(NSTimeInterval)totalTime
{
	int duration = MIN(((int)totalTime + 1), MAX_RECORDING_TIME);
	self.durationLbl.text = [NSString stringWithFormat:@"%d''", MAX(duration, 0)];
	
	CGFloat width = 0;
	CGFloat maxWidth = [HOUtils getScreenWidth] - 250;
	if(totalTime > MAX_RECORDING_TIME
 )
	{
		width = maxWidth;
	}
	else
	{
		width = MIN_AUIDO_BUBBLE_WIDTH + maxWidth * totalTime / MAX_RECORDING_TIME
;
  
	}
	width = MAX(MIN_AUIDO_BUBBLE_WIDTH, width);
	[UIView animateWithDuration:0.3 animations:^{
		self.voiceBtn.frame = CGRectMake(self.voiceBtn.frame.origin.x,
										 self.voiceBtn.frame.origin.y,
										 width,
										 self.voiceBtn.frame.size.height);
	}];
	[self updateUI];
}
- (void)updateVolumnImg:(int)index
{
	if(index <= ([[[HODefaultImage getInstance] getAudioIndicateImgArray] count] - 1))
	{
//		NSLog(@"index:%d", index);
		UIImage * imageData = [[[HODefaultImage getInstance] getAudioIndicateImgArray] objectAtIndex:index];
		self.volumnImageView.image = imageData;
	}
}
- (void)dealloc
{
	self.voiceBtn = nil;
	self.volumnImageView = nil;
	self.durationLbl = nil;
	self.recordView = nil;
	self.loadingView = nil;
	[super dealloc];
}

@end

#pragma mark
#pragma mark --

@interface HORecordView()<HOAudioPlayerDelegate>
{
}
@property(nonatomic, retain)UIButton *recordBtn;
@property(nonatomic, retain)HOVoiceView *voiceView;
@property(nonatomic, retain)HOAudioPlayer *audioPlayer;
@property(nonatomic, assign)HO_REQUEST_STATUS downloadStatus;
@property(nonatomic, assign)BOOL isRecordModal;

@end

@implementation HORecordView
@synthesize delegate;
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)initWithFrame:(CGRect)frame isRecordModal:(BOOL)isRecordModal
{
	self = [super initWithFrame:frame];
	if(self)
	{
		self.isRecordModal = isRecordModal;
		[self initSubviews];
		[self initDataSource];
		
	}
	return self;
}

- (void)initSubviews
{
	[self initRecordView];
	[self initVoiceView];
}

- (void)initDataSource
{
	self.audioPlayer = [[[HOAudioPlayer alloc] init] autorelease];
	self.audioPlayer.delegate = self;
}

- (void)initRecordView
{
	UIImage *recordImg = [UIImage imageNamed:@"ic_baoxiu_luyin"];
	UIImage *recordSelImg = [UIImage imageNamed:@"ic_baoxiu_luyin_dianji"];
	self.recordBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	self.recordBtn.frame = CGRectMake((self.frame.size.width - recordImg.size.width ) / 2,
									  HO_HORIZONAL_PADDING,
									  recordImg.size.width,
									  recordImg.size.height);
	[self.recordBtn setBackgroundImage:recordImg forState:UIControlStateNormal];
	[self.recordBtn setBackgroundImage:recordSelImg forState:UIControlStateSelected];
	[self.recordBtn setBackgroundImage:recordSelImg forState:UIControlStateHighlighted];
//	self.recordBtn.layer.borderWidth = 1;
	
	
	[self.recordBtn addTarget:self action:@selector(startRecordAudio:) forControlEvents:UIControlEventTouchDown];
	[self.recordBtn addTarget:self action:@selector(resumeAudio:) forControlEvents:UIControlEventTouchDragInside];
	[self.recordBtn addTarget:self action:@selector(pauseRecordAudio:) forControlEvents:UIControlEventTouchDragOutside];
	[self.recordBtn addTarget:self action:@selector(stopRecordAudioDontSend:) forControlEvents:UIControlEventTouchUpOutside];
	[self.recordBtn addTarget:self action:@selector(stopRecordAudio:) forControlEvents:UIControlEventTouchUpInside];
	[self.recordBtn addTarget:self action:@selector(stopRecordAudioDontSend:) forControlEvents:UIControlEventTouchCancel];
	
	[self addSubview:self.recordBtn];
	self.recordBtn.hidden = !self.isRecordModal;
	
}

- (void)removeRecord:(id)sender
{
	[self removeAudio];
}

- (void)initVoiceView
{
	CGFloat x = self.isRecordModal ? 113 : HO_HORIZONAL_PADDING;
	self.voiceView = [[[HOVoiceView alloc]
					  initWithFrame:CGRectMake(x,
											   self.isRecordModal ? 118 + 22 + HO_HORIZONAL_PADDING : 0,
											   self.frame.size.width - x - 80 - 24 - HO_HORIZONAL_PADDING,
											   50)] autorelease];
	self.voiceView.recordView = self;
//	self.voiceView.layer.borderColor = [UIColor redColor].CGColor;
//	self.voiceView.layer.borderWidth = 1;
	[self addSubview:self.voiceView];
	
	
	self.textLbl = [[[UILabel alloc] initWithFrame:CGRectMake(HO_HORIZONAL_PADDING, 128 + 10, self.frame.size.width, 22)] autorelease];
	[self addSubview:self.textLbl];
	self.textLbl.font = [UIFont systemFontOfSize:15];
	self.textLbl.textColor = TEXT_COLOR_666666;
	self.textLbl.textAlignment = NSTextAlignmentCenter;
	[self.textLbl setText:@"手指上滑, 取消发送"];
	self.textLbl.hidden = !self.isRecordModal;

}

#pragma mark
#pragma mark --

- (void)updateAudioIndicateWithPlayWithStatus:(AUDIO_PLAY_STATUS)playStatus
{
	[self.downloadDelegate updateAudioIndicateWithPlayWithStatus:playStatus];
	if(playStatus == AUDIO_PLAYING)
	{
		[self.voiceView startAudioIndication];
	}
	else if(playStatus == AUDIO_STOPED)
	{
		[self.voiceView stopAudioIndication];
	}
	else
	{
		[self.voiceView stopAudioIndication];
	}
}

- (void)disableRecord
{
//	[self.recordBtn setEnabled:NO];
	self.recordBtn.userInteractionEnabled = NO;

	
}

- (void)showLoadingWithTotalTime:(double)time
{
	[self.voiceView setTotalTime:time];
	[self.voiceView showLoading:YES];
	self.downloadStatus = HO_REQUEST_STATUS_DOING;
}


- (void)setAudioWithTotalTime:(double)totalTime withFileName:(NSString *)fileName
{
	
	[self.voiceView showLoading:NO];
	if(fileName == nil || fileName.length == 0 || totalTime == 0)
		return;
	
	[self.voiceView setTotalTime:totalTime];
	self.audioPlayer.voicePath = [HOUtils getWavAudioWithFileName:fileName];
	if([HOUtils isExistFileInLocal:self.audioPlayer.voicePath])
	{
		self.downloadStatus = HO_REQUEST_STATUS_DONE;
		[self.audioPlayer initAudioPlayerForWav];
	}
	else
	{
		self.downloadStatus = HO_REQUEST_STATUS_FAILED;
	}
	
}

- (void)testAudio:(double)totalTime withFileName:(NSString *)fileName
{
	
	[self.voiceView showLoading:NO];
	if(fileName == nil || fileName.length == 0)
		return;	self.audioPlayer.voicePath = [HOUtils getWavAudioWithFileName:fileName];
	if([HOUtils isExistFileInLocal:self.audioPlayer.voicePath])
	{
		self.downloadStatus = HO_REQUEST_STATUS_DONE;
		[self.audioPlayer initAudioPlayerForWav];
	}
	else
	{
		self.downloadStatus = HO_REQUEST_STATUS_FAILED;
	}
}

- (void)removeAudio
{
	[self.voiceView cleanup];
}

- (void)playAudio
{
	if(self.downloadStatus == HO_REQUEST_STATUS_DONE)
	{
		[self.audioPlayer playAudio];
	}
	else if(self.downloadStatus == HO_REQUEST_STATUS_DOING)
	{
		[self.downloadDelegate popupHintView:NSLocalizedString(@"语音文件正在下载。。。", @"语音文件正在下载。。。")];
	}
	else if(self.downloadStatus == HO_REQUEST_STATUS_DOING)
	{
		[self.downloadDelegate popupHintView:NSLocalizedString(@"语音文件下载失败!", @"语音文件下载失败!")];
	}
	
}

- (void)stopAudioPlay
{
	[self.audioPlayer resetPlayer];
}
#pragma mark - self delegate
-(void)forPlayTheVolume:(id)sender
{
	if ([self.delegate respondsToSelector:@selector(updateTheVolumeImage)]) {
		[self.delegate updateTheVolumeImage];
	}
}
-(void)deleteTheVolume:(id)sender
{
	if ([self.delegate respondsToSelector:@selector(deleteTheVolume)]) {
		[self.delegate deleteTheVolume];
	}
}
/**
 *  开始录音
 *
 *  @param sender
 */
-(void)startRecordAudio:(id)sender
{
	[[HOUIMgr sharedInstance] sendCommand:kHO_CMD_ClearRecord data:nil];
	if ([self.delegate respondsToSelector:@selector(begainToRecord)]) {
		[self.delegate begainToRecord];
	}
}
/**
 *  停止录音
 *
 *  @param sender
 */
-(void)stopRecordAudio:(id)sender
{
	if ([self.delegate respondsToSelector:@selector(stopRecording)]) {
		[self.delegate stopRecording];
	}
}
/**
 *  继续录音
 *
 *  @param lowPassResults
 
 */
-(void)resumeAudio:(id)sender
{
	if ([self.delegate respondsToSelector:@selector(resumesRecording)]) {
		[self.delegate resumesRecording];
	}
	
}
/**
 *  暂停录音
 *
 *  @param sender
 */
-(void)pauseRecordAudio:(id)sender
{
	if ([self.delegate respondsToSelector:@selector(pauseRecording)]) {
		[self.delegate pauseRecording];
	}
}
/**
 *  取消发送
 *
 *  @param sender
 */
-(void)stopRecordAudioDontSend:(id)sender
{
	if ([self.delegate respondsToSelector:@selector(canceleRecording)]) {
		[self.delegate canceleRecording];
	}
	
}

-(void)disPlayPlayRecordingBtn:(NSInteger)btnTag
{
//	if (btnTag == 0) {
//		_palyRecordingBtn.hidden = YES;
//		_volumeOfSoundLabel.text = @"0''";
//		_volumeOfSoundLabel.hidden = YES;
//		_deleteTheBtn.hidden = YES;
//		_recordingBtn.hidden = NO;
//	}else
//	{
//		_volumeOfSoundLabel.hidden = NO;
//		_palyRecordingBtn.hidden = NO;
//		_recordingBtn.hidden = YES;
//		_deleteTheBtn.hidden = NO;
//		[_recordingBtn addTarget:self action:@selector(deleteTheVolume:) forControlEvents:UIControlEventTouchUpInside];
//	}
}
#pragma mark
#pragma mark --
- (void)dealloc
{
	self.recordBtn = nil;
	self.voiceView = nil;
	self.audioPlayer = nil;
	self.textLbl = nil;
	[super dealloc];
}
- (void)cleanup
{
	[self.voiceView cleanup];
}

@end
